package top.yexuejc.demo;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * web服务核心
 *
 * @author maxiaofeng
 * @date 2025/6/19 11:13
 */
public class WebServer {
    Logger logger = Logger.getLogger(WebServer.class.getName());
    /** 端口 */
    private final int port;
    /** 页面资源文件 */
    private final String webRoot;
    /** 静态资源文件 */
    private final String staticRoot;

    private ServerSocket serverSocket;
    private boolean isRunning;

    public WebServer() {
        this(8080, "static", "web");
    }

    public WebServer(int port, String staticRoot, String webRoot) {
        this.port = port;
        this.staticRoot = staticRoot;
        this.webRoot = webRoot;
    }

    /**
     * 启动服务
     */
    public void start() {
        try {
            serverSocket = new ServerSocket(port);
            isRunning = true;
            logger.info("启动Web服务 : http://127.0.0.1:" + port);

            // 阻塞式监听服务是否正常
            while (isRunning) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    // 新建一个线程处理请求
                    new RequestHandler(clientSocket, staticRoot, webRoot).run();
                } catch (IOException e) {
                    if (isRunning) {
                        logger.severe("创建连接异常。");
                        e.printStackTrace();
                    }
                }
            }
        } catch (Throwable r) {
            logger.severe("启动Web服务异常。");
            r.printStackTrace();
        } finally {
            stop();
        }
    }

    /**
     * 停止服务
     */
    public void stop() {
        isRunning = false;
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e) {
            logger.info("停止Web服务异常: " + e.getMessage());
        }
        System.out.println("Web服务停止.");
    }
}
